angular.module('starter.controllers', ['ionic.rating'])


//Login Controller
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state) {
    $scope.data = {};

    /*_____   _____   _____   _____   _____   _____  
    /  ___/ /  ___| /  _  \ |  _  \ | ____| /  ___/ 
    | |___  | |     | | | | | |_| | | |__   | |___  
    \___  \ | |     | | | | |  ___/ |  __|  \___  \ 
     ___| | | |___  | |_| | | |     | |___   ___| | 
     /_____/ \_____| \_____/ |_|     |_____| /_____/  */


    $scope.bt_login = function() {
        LoginService.loginUser($scope.data.username, $scope.data.password).success(function(data) {
            $state.go('app.meineAuftraege');
            fuelleMeineAuftraege();
        }).error(function(data) {
            var alertPopup = $ionicPopup.alert({
                title: 'Login fehlgeschlagen!',
                template: 'Bitte überprüfe deine Login-Daten!'
            });
        });
    };

    $scope.bt_registrieren = function() {
        var vorname = document.getElementById("vorname").value;
        var nachname = document.getElementById("nachname").value;
        var email = document.getElementById("email").value;
        var pw1 = document.getElementById("password").value;
        var pw2 = document.getElementById("password2").value;

        if (vorname == "" || nachname == "" || email == "" || pw1 == "") {
            var alertPopup = $ionicPopup.alert({
                title: 'Hinweis:',
                template: 'Bitte alle Felder ausfüllen.'
            });
        } else if (pw1 != pw2) {
            var alertPopup = $ionicPopup.alert({
                title: 'Hinweis:',
                template: 'Die eingegebenen Passwörter stimmen nicht überein.'
            });
        } else {
            jQuery.post("http://ba.tech-time.de/kurier/json.php", {
                    action: "register",
                    userEmail: email,
                    userFirstname: vorname,
                    userLastname: nachname,
                    userPassword: pw1
                },
                function(data) {
                    var obj = jQuery.parseJSON(data);
                    if (obj.errorcode == 0) {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Registrierung erfolgreich',
                            template: 'Schau gleich in dein E-Mail Postfach.'
                        });
                        $state.go('login');
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Die Registrierung konnte nicht abgeschlossen werden.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                });
        }
    };

    //Passwort zurücksetzen
    $scope.bt_resetPassword = function() {
        var email = document.getElementById("emailpwvergessen").value;
        if (email == "")
            var alertPopup = $ionicPopup.alert({
                title: 'Hinweis',
                template: 'Bitte E-Mail Adresse eingeben.'
            });
        else {
            jQuery.post("http://ba.tech-time.de/kurier/json.php", {
                    action: "resetPassword",
                    userEmail: email
                },
                function(data) {
                    var obj = jQuery.parseJSON(data);
                    if (obj.errorcode == 0) {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Neues Passwort',
                            template: 'Dir wurde dein neues Passwort zugeschickt.'
                        });
                        $state.go('login');
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Dir wurde kein neues Passwort zugeschickt.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                });
        }
    };

    $scope.gohome = function() {
        $state.go('home');
    };

    $scope.gologin = function() {
        $state.go('login');
    };

    $scope.gopwVergessen = function() {
        $state.go('pwVergessen');
    };

    $scope.goregistrieren = function() {
        $state.go('registrieren');
    };

    $scope.refreshMeineAuftraegeAnzeigen = function() {
        fuelleMeineAuftraege();
        $scope.$broadcast('scroll.refreshComplete');
    };




    /*
     _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
    |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
    | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
    |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
    | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
    |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();



    function createTableMeineAuftraege(typ, start, ziel, status, id) {

        var div = document.createElement("div");
        div.className = "row";
        div.id = id;

        var div2 = document.createElement("div");
        div2.className = "col col_narrow col_symbol";
        if (typ == "agent")
            div2.innerHTML = '<i class="icon ion-android-bicycle"></i>';
        else
            div2.innerHTML = '<i class="ion-ios-body"></i>';

        var div3 = document.createElement("div");
        div3.className = "col";
        div3.innerHTML = start;

        var div4 = document.createElement("div");
        div4.className = "col";
        div4.innerHTML = ziel;

        var div5 = document.createElement("div");
        div5.className = "col";
        div5.innerHTML = status;

        div.appendChild(div2);
        div.appendChild(div3);
        div.appendChild(div4);
        div.appendChild(div5);

        $(div).bind('tap', function(event, ui) {

            meineAuftraegeDetails(id);

        });

        return div;
    }

    function driveChangeStatus(dID, status) {
        var dUID = device.uuid;
        var sessionID = fromLocalStorage("sessionID");
        var sessionUId = fromLocalStorage("sessionUId");
        $.post("http://ba.tech-time.de/kurier/json.php", {
                action: "driveChangeStatus",
                sessionDeviceId: dUID,
                sessionUId: sessionUId,
                sessionId: sessionID,
                driveId: dID,
                driveStatus: status
            },
            function(data) {
                var obj = jQuery.parseJSON(data);
                if (obj.errorcode == 0) {
                    $state.go('app.meineAuftraege');
                    fuelleMeineAuftraege();
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Auftrag konnte nicht aktualisiert werden.<br />Systemnachricht: ' + obj.errormessage
                    });
                }
            });
    }

    function fuelleMeineAuftraege() {
        if (checkSession() == true) {
            showAllUserDrives(fromLocalStorage("sessionUId"), function(obj) {
                if (obj) {
                    node = document.getElementById("rowsMeineAuftraege");
                    while (node.firstChild) {
                        node.removeChild(node.firstChild);
                    }
                    if (obj.errorcode == 0) {

                        if (obj.drives != "") {
                            for (var item in obj.drives) {
                                if (!isNumber(obj.drives)) {
                                    var typ = getAuftragsTyp(fromLocalStorage("sessionUId"), obj.drives[item].userAgent, obj.drives[item].userPrincipal);
                                    node.appendChild(createTableMeineAuftraege(typ, obj.drives[item].startLoc.city, obj.drives[item].endLoc.city, obj.drives[item].status, obj.drives[item].id), node.nextSibling);
                                }
                            }
                        } else {
                            node.innerHTML = "<p>Derzeit sind leider keine Auftraege vorhanden.</p>";
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });
                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }



    function meineAuftraegeDetails(dID) {
        $state.go('app.meineAuftraegeDetails');
        if (checkSession() == true) {

            showDrive(fromLocalStorage("sessionUId"), dID, function(obj) {
                if (obj) {
                    if (obj.errorcode == 0) {
                        initializeMeine(obj.drive.startLoc.gps_l, obj.drive.startLoc.gps_w, obj.drive.endLoc.gps_l, obj.drive.endLoc.gps_w);

                        var statusnr = obj.drive.statusnr;
                        var agent = obj.drive.userAgent;
                        var principal = obj.drive.userPrincipal;
                        var user = fromLocalStorage("sessionUId");

                        document.getElementById("start1").innerHTML = obj.drive.startLoc.street + " " + obj.drive.startLoc.number + "<br />" + obj.drive.startLoc.postal + " " + obj.drive.startLoc.city;
                        document.getElementById("ziel1").innerHTML = obj.drive.endLoc.street + " " + obj.drive.endLoc.number + "<br />" + obj.drive.endLoc.postal + " " + obj.drive.endLoc.city;
                        document.getElementById("distanz1").innerHTML = obj.drive.distance + "km";
                        document.getElementById("preis1").innerHTML = obj.drive.price + "€";
                        document.getElementById("startzeit1").innerHTML = fromUnixTimeToString(obj.drive.startTime);
                        document.getElementById("endzeit1").innerHTML = fromUnixTimeToString(obj.drive.endTime);
                        document.getElementById("status1").innerHTML = obj.drive.status;

                        var div = document.getElementById("meineAuftraegeDiv");
                        while (div.firstChild) {
                            div.removeChild(div.firstChild);
                        }

                        var btnone = document.createElement("button");
                        btnone.className = "button button-positive button-block";
                        btnone.id = "btnMeineAuftraege" + obj.drive.id;

                        if ((statusnr == 1 || statusnr == 2 || statusnr == 3) && user == principal) {
                            btnone.innerHTML = "Auftrag stornieren";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 6);
                            });
                            div.appendChild(btnone);
                        } else if ((statusnr == 3) && user == agent) {
                            btnone.innerHTML = "Auftrag starten";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 4);
                            });

                            div.appendChild(btnone);

                            var btntwo = document.createElement("button");
                            btntwo.className = "button button-positive button-block";
                            btntwo.id = "btnMeineAuftraegeTwo" + obj.drive.id;

                            btntwo.innerHTML = "Auftrag stornieren";
                            $(btntwo).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 2);
                            });

                            div.appendChild(btntwo);
                        } else if ((statusnr == 4) && user == agent) {
                            btnone.innerHTML = "Auftrag fertig";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 5);
                            });
                            div.appendChild(btnone);
                        } else if (statusnr == 5) {
                            btnone.innerHTML = "Auftrag bewerten";
                            $(btnone).bind('tap', function(event, ui) {
                                alert("TODO");
                            });
                            div.appendChild(btnone);
                        } else if (statusnr == 6 && user == principal) {
                            btnone.innerHTML = "Auftrag erneut einstellen";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 2);
                            });
                            div.appendChild(btnone);
                        }

                        $scope.data.auftragID = dID;
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }




                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });


        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }
        function initializeMeine(startLat, startLng, endLat, endLng) {

        directionsDisplay = new google.maps.DirectionsRenderer();
        var endLoc = new google.maps.LatLng(endLat, endLng);

        var mapOptions = {
            zoom: 8,
            center: endLoc
        };
        var map = new google.maps.Map(document.getElementById('map-canvas3'), mapOptions);
        directionsDisplay.setMap(map);

        calcRoute(new google.maps.LatLng(startLat, startLng), new google.maps.LatLng(endLat, endLng));
    }

        function calcRoute(start, end) {


        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.BICYCLING,
            unitSystem: google.maps.UnitSystem.METRIC
        };

        directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(result);
                var distance = getDistanceFromRoute(result);
                var duration = getDurationFromRoute(result);
                console.log("Distance: " + distance + " Duration: " + duration);
            } else {
                console.log("error while calculating route");
            }
        });
    }

})







.controller('selectDestinationCtrl', function($scope, $ionicLoading, $ionicPopup, $state, $timeout) {

    /*_____   _____   _____   _____   _____   _____  
    /  ___/ /  ___| /  _  \ |  _  \ | ____| /  ___/ 
    | |___  | |     | | | | | |_| | | |__   | |___  
    \___  \ | |     | | | | |  ___/ |  __|  \___  \ 
     ___| | | |___  | |_| | | |     | |___   ___| | 
     /_____/ \_____| \_____/ |_|     |_____| /_____/  */

    var d = new Date(fromLocalStorage("auftragFromUnixTime") * 1000);

    $scope.toDate = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    $scope.toTime = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());

    $scope.aktPositionTo = function() {
        toLocalStorage("fromOrTo", "to");
        $ionicLoading.show({
            content: 'Loading',
            animation: 'fade-in',
            showBackdrop: true,
            maxWidth: 200,
            showDelay: 0
        });
        getGeoLocation();
        $ionicLoading.hide();
    };

    $scope.bt_auftragAufgeben = function() {

        if (checkSession() == true) {

            var auftragToName = document.getElementById("auftrag.to.name").value;
            var auftragToStrasse = document.getElementById("auftrag.to.strasse").value;
            var auftragToHausn = document.getElementById("auftrag.to.hausn").value;
            var auftragToPlz = document.getElementById("auftrag.to.plz").value;
            var auftragToOrt = document.getElementById("auftrag.to.ort").value;
            var auftragToUhrzeit = document.getElementById("auftrag.to.uhrzeit").value;
            var auftragToDatum = document.getElementById("auftrag.to.datum").value;
            var auftragPreis = document.getElementById("auftrag.preis").value;

            if (auftragPreis != "" && auftragPreis > 0 && auftragToStrasse != "" && auftragToHausn != "" && auftragToPlz != "" && auftragToOrt != "" && auftragToUhrzeit != "" && auftragToDatum != "" && auftragToUnixTime != "") {

                var auftragToUnixTime = toUnixTime(auftragToDatum, auftragToUhrzeit);
                toLocalStorage("auftragToUnixTime", auftragToUnixTime);

                //Adresse in GPS umwandeln und LocationID in Local Storage speichern
                addressToGps(auftragToStrasse + "," + auftragToHausn + "," + auftragToPlz + "," + auftragToOrt, function(coords) {
                    if (coords) {
                        toLocalStorage("lngTo", coords.lng());
                        toLocalStorage("latTo", coords.lat());
                        var locIdTo = locationAdd(fromLocalStorage("sessionUId"), auftragToOrt, auftragToName, coords.lng(), coords.lat(), auftragToHausn, auftragToPlz, auftragToStrasse);
                        if (locIdTo != 0) {
                            toLocalStorage("locationIdTo", locIdTo);
                            // Wenn fertig, gehe zur nächsten Seite
                            getDistanceFromRoute(new google.maps.LatLng(fromLocalStorage("latFrom"), fromLocalStorage("lngFrom")), new google.maps.LatLng(fromLocalStorage("latTo"), fromLocalStorage("lngTo")),
                                function(distance) {

                                    dist = distance.replace("km", "");
                                    dist = dist.replace(" ", "");
                                    dist = dist.replace(",", ".");

                                    driveAdd(fromLocalStorage("sessionUId"), dist, fromLocalStorage("locationIdTo"), fromLocalStorage("auftragToUnixTime"), auftragPreis, fromLocalStorage("locationIdFrom"), fromLocalStorage("auftragFromUnixTime"), 2, function(obj) {
                                        if (obj) {

                                            if (obj.errorcode == 0) {
                                                var alertPopup = $ionicPopup.alert({
                                                    title: 'ERFOLG',
                                                    template: 'Der Auftrag wurde erfolgreich angelegt!'
                                                });
                                            } else {
                                                var alertPopup = $ionicPopup.alert({
                                                    title: 'Fehler',
                                                    template: 'Der Auftrag konnte nicht angelegt werden!<br />Systemnachricht: ' + obj.errormessage
                                                });
                                            }


                                            $state.go('app.meineAuftraege');
                                        } else {
                                            var alertPopup = $ionicPopup.alert({
                                                title: 'Fehler',
                                                template: 'Fehler beim anlegen Ihres Auftrags. Bitte eigegebene Daten Prüfen!'
                                            });
                                        }



                                    });
                                });

                        } else {
                            var alertPopup = $ionicPopup.alert({
                                title: 'Fehler',
                                template: 'Adresse konnte nicht in die Datenbank eingefuegt werden!'
                            });
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Unbekannte Adresse!'
                        });

                    }
                });


            } else {
                var alertPopup = $ionicPopup.alert({
                    title: 'Fehler',
                    template: 'Bitte alle Felder ausfüllen!'
                });

            }

        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });
            $state.go('login');
        }
    };

    /*
     _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
    |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
    | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
    |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
    | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
    |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */

    function getGeoLocation() {

        var options = {
            maximumAge: 0,
            timeout: 10000
        };
        navigator.geolocation.getCurrentPosition(onSuccessGeolocation, onErrorGeolocation, options);
    }

    function gpsToAddress(lat, lng) {

        latlng = new google.maps.LatLng(lat, lng);

        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({
            'latLng': latlng
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var result = results[0];
                    var obj = getObjectFromAddress(result);
                    fuelleOrtFelder(obj);
                }

            } else {

                var alertPopup = $ionicPopup.alert({
                    title: 'Fehler',
                    template: 'Geocoder failed due to: ' + status
                });


            }
        });
    }

    // onError CallFback receives a PositionError object
    //
    function onErrorGeolocation(error) {

        var alertPopup = $ionicPopup.alert({
            title: 'Fehler',
            template: '' + error.message + '\n'
        });
    }

    function onSuccessGeolocation(position) {
        lat = position.coords.latitude;
        lng = position.coords.longitude;
        gpsToAddress(lat, lng);
    }
})

.controller('bewertungCtrl', function($scope, $state, $timeout) {
    // set the rate and max variables
  $scope.rate = 3;
  $scope.max = 5;

})







.controller('auftragAufgebenCtrl', function($scope, $ionicLoading, $ionicPopup, $state, $timeout, $ionicTabsDelegate) {
    /*_____   _____   _____   _____   _____   _____  
    /  ___/ /  ___| /  _  \ |  _  \ | ____| /  ___/ 
    | |___  | |     | | | | | |_| | | |__   | |___  
    \___  \ | |     | | | | |  ___/ |  __|  \___  \ 
     ___| | | |___  | |_| | | |     | |___   ___| | 
     /_____/ \_____| \_____/ |_|     |_____| /_____/  */

    var d = new Date();

    $scope.fromDate = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    $scope.fromTime = new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds());

    $scope.aktPositionFrom = function() {
        toLocalStorage("fromOrTo", "from");

        $ionicLoading.show({
            content: 'Loading',
            animation: 'fade-in',
            showBackdrop: true,
            maxWidth: 200,
            showDelay: 0
        });

        getGeoLocation();
        $ionicLoading.hide();
    };

    $scope.bt_weiterSelectDestination = function() {
        if (checkSession() == true) {

            var auftragFromName = document.getElementById("auftrag.from.name").value;
            var auftragFromStrasse = document.getElementById("auftrag.from.strasse").value;
            var auftragFromHausn = document.getElementById("auftrag.from.hausn").value;
            var auftragFromPlz = document.getElementById("auftrag.from.plz").value;
            var auftragFromOrt = document.getElementById("auftrag.from.ort").value;
            var auftragFromUhrzeit = document.getElementById("auftrag.from.uhrzeit").value;
            var auftragFromDatum = document.getElementById("auftrag.from.datum").value;

            if (auftragFromStrasse != "" && auftragFromHausn != "" && auftragFromPlz != "" && auftragFromOrt != "" && auftragFromUhrzeit != "" && auftragFromDatum != "" && auftragFromUnixTime != "") {

                var auftragFromUnixTime = toUnixTime(auftragFromDatum, auftragFromUhrzeit);
                toLocalStorage("auftragFromUnixTime", auftragFromUnixTime);

                //Adresse in GPS umwandeln und LocationID in Local Storage speichern
                addressToGps(auftragFromStrasse + "," + auftragFromHausn + "," + auftragFromPlz + "," + auftragFromOrt, function(coords) {
                    if (coords) {
                        toLocalStorage("lngFrom", coords.lng());
                        toLocalStorage("latFrom", coords.lat());
                        var locIdFrom = locationAdd(fromLocalStorage("sessionUId"), auftragFromOrt, auftragFromName, coords.lng(), coords.lat(), auftragFromHausn, auftragFromPlz, auftragFromStrasse);
                        if (locIdFrom != 0) {
                            toLocalStorage("locationIdFrom", locIdFrom);
                            // Wenn fertig, gehe zur nächsten Seite
                            $state.go('app.selectDestination');
                        } else {
                            var alertPopup = $ionicPopup.alert({
                                title: 'Fehler',
                                template: 'Adresse konnte nicht in die Datenbank eingefuegt werden!'
                            });
                        }

                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Unbekannte Adresse!'
                        });

                    }
                });


            } else {
                var alertPopup = $ionicPopup.alert({
                    title: 'Fehler',
                    template: 'Bitte alle Felder ausfüllen!'
                });

            }

        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    };

    /*
     _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
    |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
    | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
    |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
    | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
    |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */

    function getGeoLocation() {

        var options = {
            maximumAge: 0,
            timeout: 10000
        };
        navigator.geolocation.getCurrentPosition(onSuccessGeolocation, onErrorGeolocation, options);
    }

    function gpsToAddress(lat, lng) {

            latlng = new google.maps.LatLng(lat, lng);

            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({
                'latLng': latlng
            }, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    if (results[0]) {
                        var result = results[0];
                        var obj = getObjectFromAddress(result);
                        fuelleOrtFelder(obj);
                    }

                } else {

                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Geocoder failed due to: ' + status
                    });


                }
            });
        }
        // onError CallFback receives a PositionError object
        //

    function onErrorGeolocation(error) {

        var alertPopup = $ionicPopup.alert({
            title: 'Fehler',
            template: '' + error.message + '\n'
        });
    }

    function onSuccessGeolocation(position) {
        lat = position.coords.latitude;
        lng = position.coords.longitude;
        gpsToAddress(lat, lng);
    }
})






.controller('meineAuftraegeCtrl', function($scope, $ionicPopup, $state, $timeout, $ionicModal) {

    $ionicModal.fromTemplateUrl('modalMeineAuftraege.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.modal = modal;
    });

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

    /*_____   _____   _____   _____   _____   _____  
    /  ___/ /  ___| /  _  \ |  _  \ | ____| /  ___/ 
    | |___  | |     | | | | | |_| | | |__   | |___  
    \___  \ | |     | | | | |  ___/ |  __|  \___  \ 
     ___| | | |___  | |_| | | |     | |___   ___| | 
     /_____/ \_____| \_____/ |_|     |_____| /_____/  */

    $scope.openModal = function() {
        $scope.modal.show();
    };
    $scope.closeModal = function() {
        $scope.modal.hide();
    };
    $scope.removeModal = function() {
        $scope.modal.remove();
    };

    $scope.refreshMeineAuftraegeAnzeigen = function() {
        fuelleMeineAuftraege();
        $scope.$broadcast('scroll.refreshComplete');
    };

    $scope.filtern = function() {
            console.log(jQuery("#bba").val());
        }
        /*
         _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
        |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
        | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
        |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
        | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
        |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */


   

    function createTableMeineAuftraege(typ, start, ziel, status, id) {

        var div = document.createElement("div");
        div.className = "row";
        div.id = id;

        var div2 = document.createElement("div");
        div2.className = "col col_narrow col_symbol";
        if (typ == "agent")
            div2.innerHTML = '<i class="icon ion-android-bicycle"></i>';
        else
            div2.innerHTML = '<i class="ion-ios-body"></i>';

        var div3 = document.createElement("div");
        div3.className = "col";
        div3.innerHTML = start;

        var div4 = document.createElement("div");
        div4.className = "col";
        div4.innerHTML = ziel;

        var div5 = document.createElement("div");
        div5.className = "col";
        div5.innerHTML = status;

        div.appendChild(div2);
        div.appendChild(div3);
        div.appendChild(div4);
        div.appendChild(div5);

        $(div).bind('tap', function(event, ui) {

            meineAuftraegeDetails(id);

        });

        return div;
    }

    function driveChangeStatus(dID, status) {
        var dUID = device.uuid;
        var sessionID = fromLocalStorage("sessionID");
        var sessionUId = fromLocalStorage("sessionUId");
        $.post("http://ba.tech-time.de/kurier/json.php", {
                action: "driveChangeStatus",
                sessionDeviceId: dUID,
                sessionUId: sessionUId,
                sessionId: sessionID,
                driveId: dID,
                driveStatus: status
            },
            function(data) {
                var obj = jQuery.parseJSON(data);
                if (obj.errorcode == 0) {
                    $state.go('app.meineAuftraege');
                    fuelleMeineAuftraege();
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Auftrag konnte nicht aktualisiert werden.<br />Systemnachricht: ' + obj.errormessage
                    });
                }
            });
    }

    function fuelleMeineAuftraege() {
        if (checkSession() == true) {
            showAllUserDrives(fromLocalStorage("sessionUId"), function(obj) {
                if (obj) {
                    node = document.getElementById("rowsMeineAuftraege");
                    while (node.firstChild) {
                        node.removeChild(node.firstChild);
                    }
                    if (obj.errorcode == 0) {

                        if (obj.drives != "") {
                            for (var item in obj.drives) {
                                if (!isNumber(obj.drives)) {
                                    var typ = getAuftragsTyp(fromLocalStorage("sessionUId"), obj.drives[item].userAgent, obj.drives[item].userPrincipal);
                                    node.appendChild(createTableMeineAuftraege(typ, obj.drives[item].startLoc.city, obj.drives[item].endLoc.city, obj.drives[item].status, obj.drives[item].id), node.nextSibling);
                                }
                            }
                        } else {
                            node.innerHTML = "<p>Derzeit sind leider keine Auftraege vorhanden.</p>";
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });
                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }



    function meineAuftraegeDetails(dID) {
        $state.go('app.meineAuftraegeDetails');
        if (checkSession() == true) {

            showDrive(fromLocalStorage("sessionUId"), dID, function(obj) {
                if (obj) {
                    if (obj.errorcode == 0) {
                        initializeMeine(obj.drive.startLoc.gps_l, obj.drive.startLoc.gps_w, obj.drive.endLoc.gps_l, obj.drive.endLoc.gps_w);

                        var statusnr = obj.drive.statusnr;
                        var agent = obj.drive.userAgent;
                        var principal = obj.drive.userPrincipal;
                        var user = fromLocalStorage("sessionUId");

                        document.getElementById("start1").innerHTML = obj.drive.startLoc.street + " " + obj.drive.startLoc.number + "<br />" + obj.drive.startLoc.postal + " " + obj.drive.startLoc.city;
                        document.getElementById("ziel1").innerHTML = obj.drive.endLoc.street + " " + obj.drive.endLoc.number + "<br />" + obj.drive.endLoc.postal + " " + obj.drive.endLoc.city;
                        document.getElementById("distanz1").innerHTML = obj.drive.distance + "km";
                        document.getElementById("preis1").innerHTML = obj.drive.price + "€";
                        document.getElementById("startzeit1").innerHTML = fromUnixTimeToString(obj.drive.startTime);
                        document.getElementById("endzeit1").innerHTML = fromUnixTimeToString(obj.drive.endTime);
                        document.getElementById("status1").innerHTML = obj.drive.status;

                        var div = document.getElementById("meineAuftraegeDiv");
                        while (div.firstChild) {
                            div.removeChild(div.firstChild);
                        }

                        var btnone = document.createElement("button");
                        btnone.className = "button button-positive button-block";
                        btnone.id = "btnMeineAuftraege" + obj.drive.id;

                        if ((statusnr == 1 || statusnr == 2 || statusnr == 3) && user == principal) {
                            btnone.innerHTML = "Auftrag stornieren";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 6);
                            });
                            div.appendChild(btnone);
                        } else if ((statusnr == 3) && user == agent) {
                            btnone.innerHTML = "Auftrag starten";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 4);
                            });

                            div.appendChild(btnone);

                            var btntwo = document.createElement("button");
                            btntwo.className = "button button-positive button-block";
                            btntwo.id = "btnMeineAuftraegeTwo" + obj.drive.id;

                            btntwo.innerHTML = "Auftrag stornieren";
                            $(btntwo).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 2);
                            });

                            div.appendChild(btntwo);
                        } else if ((statusnr == 4) && user == agent) {
                            btnone.innerHTML = "Auftrag fertig";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 5);
                            });
                            div.appendChild(btnone);
                        } else if (statusnr == 5) {
                            btnone.innerHTML = "Auftrag bewerten";
                            $(btnone).bind('tap', function(event, ui) {
                                alert("TODO");
                            });
                            div.appendChild(btnone);
                        } else if (statusnr == 6 && user == principal) {
                            btnone.innerHTML = "Auftrag erneut einstellen";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 2);
                            });
                            div.appendChild(btnone);
                        }

                        $scope.data.auftragID = dID;
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }




                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });


        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }


        function initializeDetails(startLat, startLng, endLat, endLng) {

        directionsDisplay = new google.maps.DirectionsRenderer();
        var endLoc = new google.maps.LatLng(endLat, endLng);

        var mapOptions = {
            zoom: 8,
            center: endLoc
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        directionsDisplay.setMap(map);

        calcRoute(new google.maps.LatLng(startLat, startLng), new google.maps.LatLng(endLat, endLng));
    }
    function initializeMeine(startLat, startLng, endLat, endLng) {

        directionsDisplay = new google.maps.DirectionsRenderer();
        var endLoc = new google.maps.LatLng(endLat, endLng);

        var mapOptions = {
            zoom: 8,
            center: endLoc
        };
        var map = new google.maps.Map(document.getElementById('map-canvas3'), mapOptions);
        directionsDisplay.setMap(map);

        calcRoute(new google.maps.LatLng(startLat, startLng), new google.maps.LatLng(endLat, endLng));
    }

         function calcRoute(start, end) {


        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.BICYCLING,
            unitSystem: google.maps.UnitSystem.METRIC
        };

        directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(result);
                var distance = getDistanceFromRoute(result);
                var duration = getDurationFromRoute(result);
                console.log("Distance: " + distance + " Duration: " + duration);
            } else {
                console.log("error while calculating route");
            }
        });
    }


})








.controller('meineAuftraegeDetailsCtrl', function($scope, $ionicModal, $ionicPopup, $state, $timeout) {})
.controller('profilAendernCtrl', function($scope, $ionicModal, $ionicPopup, $state, $timeout) {})






.controller('auftragAnzeigenCtrl', function($scope, $ionicModal, $ionicPopup, $state, $timeout, $ionicTabsDelegate) {

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

    $scope.data = {
        levelvalue: 25,
        disableFileds: false,
        mapInitialized: false,
        umkreis:false
    };

    $ionicModal.fromTemplateUrl('contact-modal.html', {
        scope: $scope,
        animation: 'slide-in-up'
    }).then(function(modal) {
        $scope.modal = modal;
    });

    



    /*_____   _____   _____   _____   _____   _____  
    /  ___/ /  ___| /  _  \ |  _  \ | ____| /  ___/ 
    | |___  | |     | | | | | |_| | | |__   | |___  
    \___  \ | |     | | | | |  ___/ |  __|  \___  \ 
     ___| | | |___  | |_| | | |     | |___   ___| | 
     /_____/ \_____| \_____/ |_|     |_____| /_____/  */

    $scope.changeMyThings = function() {

        if ($scope.data.disableFileds == true) {
            $scope.data.disableFileds = false;
        } else {
            $scope.data.disableFileds = true;
        }
    };

    $scope.closeModal = function() {
        $scope.modal.hide();
    };

    $scope.filter = function() {

        if ($scope.data.disableFileds == false) {
            var stadt = document.getElementById("inputStadt").value;
            var strasse = document.getElementById("inputStrasse").value;
            if (stadt != "" && strasse != "") {
                addressToGps(strasse + "," + stadt, function(coords) {
                    if (coords) {

                        fuelleAuftragAnzeigenUmkreis($scope.data.levelvalue, coords.lat(), coords.lng());
        
                        $scope.closeModal();
                        

                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Unbekannte Adresse!'
                        });
                    }
                });
            } else {
                var alertPopup = $ionicPopup.alert({
                    title: 'Fehler',
                    template: 'Bitte Adresse ausfüllen oder GPS auswählen!'
                });
            }
        } else {
            navigator.geolocation.getCurrentPosition(onSuccessGeo, onErrorGeo);
        }
    };

    $scope.openModal = function() {
        $scope.modal.show();
    };


    $scope.refreshAuftragAnzeigen = function() {
        fuelleAuftragAnzeigen();
       
        $scope.$broadcast('scroll.refreshComplete');
    };

    $scope.refreshAuftragAnzeigenMap = function() {
        deleteMarkers();
        map();
        $scope.$broadcast('scroll.refreshComplete');
    };

    $scope.initMap = function() {
        map();
    }

    $scope.removeModal = function() {
        $scope.modal.remove();
    };

    $scope.setLevelText = function() {
        console.log('range value has changed to :' + $scope.data.levelvalue);
        $scope.data.testvariable = $scope.data.levelvalue;
    }



    /*
     _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
    |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
    | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
    |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
    | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
    |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */

    var map2;
    var markers = [];
    var circle;

    function map() {

        if ($scope.data.mapInitialized == false) {

            console.log("map erzeugen");
            var directionsDisplay1 = new google.maps.DirectionsRenderer();

            var loc = new google.maps.LatLng(50.111512, 8.680506);

            var mapOptions2 = {
                zoom: 8,
                center: loc
            };

            map2 = new google.maps.Map(document.getElementById('map-canvas2'), mapOptions2);

            directionsDisplay1.setMap(map2);

            deleteMarkers();
            navigator.geolocation.getCurrentPosition(onSuccessGeoMap, onErrorGeoMap);     

            $scope.data.mapInitialized = true;
        } else {

            if(circle)
            circle.setMap(null);

            deleteMarkers();

            navigator.geolocation.getCurrentPosition(onSuccessGeoMap, onErrorGeoMap);
        }
    }
    function onSuccessGeoMap(position){
        lat = position.coords.latitude;
        lng = position.coords.longitude;

        mapCirlce(500,lat, lng);
        fuelleAuftragAnzeigenMapUmkreis(50,lat, lng);

    }
    function onErrorGeoMap(){
        fuelleAuftragAnzeigenMap();
    }

    function auftragDetails(dID) {
        $state.go('app.auftragDetails');
        if (checkSession() == true) {

            showDrive(fromLocalStorage("sessionUId"), dID, function(obj) {
                if (obj) {
                    if (obj.errorcode == 0) {
                        initializeDetails(obj.drive.startLoc.gps_l, obj.drive.startLoc.gps_w, obj.drive.endLoc.gps_l, obj.drive.endLoc.gps_w);

                        document.getElementById("start").innerHTML = obj.drive.startLoc.street + " " + obj.drive.startLoc.number + "<br />" + obj.drive.startLoc.postal + " " + obj.drive.startLoc.city;
                        document.getElementById("ziel").innerHTML = obj.drive.endLoc.street + " " + obj.drive.endLoc.number + "<br />" + obj.drive.endLoc.postal + " " + obj.drive.endLoc.city;
                        document.getElementById("distanz").innerHTML = obj.drive.distance + "km";
                        document.getElementById("preis").innerHTML = obj.drive.price + "€";
                        document.getElementById("startzeit").innerHTML = fromUnixTimeToString(obj.drive.startTime);
                        document.getElementById("endzeit").innerHTML = fromUnixTimeToString(obj.drive.endTime);

                        $scope.data.auftragID = dID;
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Aktion gerade nicht möglich.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });
                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });
            $state.go('login');
        }
    }

    

    function createTable(entfernung, start, strecke, preis, endzeit, id, userPrincipal) {


        var div = document.createElement("div");
        div.className = "row";
        div.id = id;


        var div2 = document.createElement("div");
        div2.className = "col";
        if (entfernung == 0) {
            div2.innerHTML = "N/A";
        } else {
            div2.innerHTML = entfernung + " Km";
        }

        var div3 = document.createElement("div");
        div3.className = "col";
        div3.innerHTML = start;

        var div4 = document.createElement("div");
        div4.className = "col";
        div4.innerHTML = strecke + "km";

        var div5 = document.createElement("div");
        div5.className = "col";
        div5.innerHTML = preis + "€";

        var div6 = document.createElement("div");
        div6.className = "col";
        div6.innerHTML = fromUnixTimeToString(endzeit);


        div.appendChild(div2);
        div.appendChild(div3);
        div.appendChild(div4);
        div.appendChild(div5);
        div.appendChild(div6);

        $(div).bind('tap', function(event, ui) {

            auftragDetails(id);

        });

        if (userPrincipal == fromLocalStorage("sessionUId")) {
            div.className = "row stable-bg";
            console.log("eigener");
        }

        return div;
    }

    function fuelleAuftragAnzeigen() {
        if (checkSession() == true) {
            showOpenDrives(fromLocalStorage("sessionUId"), 0, 0, 0, function(obj) {
                if (obj) {
                    node = document.getElementById("rows");
                    while (node.firstChild) {
                        node.removeChild(node.firstChild);
                    }
                    if (obj.errorcode == 0) {
                        if (obj.drives != "") {
                            for (var item in obj.drives) {
                                node.appendChild(createTable(0, obj.drives[item].endLoc.city, obj.drives[item].distance, obj.drives[item].price, obj.drives[item].endTime, obj.drives[item].id, obj.drives[item].userPrincipal), node.nextSibling);
                            }
                        } else {
                            node.innerHTML = "<p>Derzeit sind keine Auftraege vorhanden.</p>";
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }

                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }

    function fuelleAuftragAnzeigenMap() {
        if (checkSession() == true) {
            showOpenDrives(fromLocalStorage("sessionUId"), 0, 0, 0, function(obj) {
                if (obj) {
                    if (obj.drives != "") {
                        
                        for (var item in obj.drives) {
                            fillMap(obj.drives[item].id, obj.drives[item].endLoc.gps_l, obj.drives[item].endLoc.gps_w);
                        }
                    } else {
                        //node.innerHTML = "<p>Derzeit sind keine Auftraege vorhanden.</p>";
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }

    function fuelleAuftragAnzeigenMapUmkreis(driveRange, lat, lng) {
        if (checkSession() == true) {
            showOpenDrives(fromLocalStorage("sessionUId"), driveRange, lat, lng, function(obj) {
                if (obj) {
                    if (obj.drives != "") {
                        // map();
                        for (var item in obj.drives) {
                            /* node.appendChild(createTable(0, obj.drives[item].startLoc.city, obj.drives[item].distance, obj.drives[item].price, obj.drives[item].endTime, obj.drives[item].id, obj.drives[item].userPrincipal), node.nextSibling);
                             */
                            /* console.log(obj.drives[item].id+ " id");
                             console.log(obj.drives[item].endLoc.gps_l+ " gps_l");
                             console.log(obj.drives[item].endLoc.gps_w+ " gps_w");*/
                            fillMap(obj.drives[item].id, obj.drives[item].endLoc.gps_l, obj.drives[item].endLoc.gps_w);
                        }
                    } else {
                        //node.innerHTML = "<p>Derzeit sind keine Auftraege vorhanden.</p>";
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }

    function mapCirlce(driveRange, lat, lng) {

        var latLng = new google.maps.LatLng(lat, lng);
       
        var img= 'templates/assets/marker-40.png';
        var marker = new google.maps.Marker({
            map: map2,
            position: latLng,
            title: 'Some location',
            animation:google.maps.Animation.BOUNCE,
            icon: img

        });
        // marker.setMap(map2);

        markers.push(marker);
        // Add circle overlay and bind to marker
        circle = new google.maps.Circle({
            map: map2,
            radius: driveRange * 100, // 10 miles in metres
            strokeColor: "#0000FF",
            fillColor: "#0000FF"

        });
        circle.bindTo('center', marker, 'position');

    }

    function fillMap(id, lat, lng) {


        var latLng = new google.maps.LatLng(lat, lng);
        console.log("latlng " + latLng);
        var marker = new google.maps.Marker({
            map: map2,
            position: latLng,
            title: 'Some location',
            animation:google.maps.Animation.DROP,
        });
        markers.push(marker);

        google.maps.event.addListener(marker, 'click', function() {
            auftragDetails(id);

        });
    }

    function setAllMap(map) {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(map);
        }
    }

    // Removes the markers from the map, but keeps them in the array.
    function clearMarkers() {
        setAllMap(null);
    }

    function deleteMarkers() {
        clearMarkers();
        markers = [];
    }

    function fuelleAuftragAnzeigenUmkreis(driveRange, lat, lng) {
        if (checkSession() == true) {
            showOpenDrives(fromLocalStorage("sessionUId"), driveRange, lat, lng, function(obj) {
                if (obj) {
                    node = document.getElementById("rows");
                    while (node.firstChild) {
                        node.removeChild(node.firstChild);
                    }
                    if (obj.errorcode == 0) {

                        if (obj.drives != "") {
                            for (var item in obj.drives) {
                                node.appendChild(createTable(obj.drives[item].distanceToStart, obj.drives[item].endLoc.city, obj.drives[item].distance, obj.drives[item].price, obj.drives[item].endTime, obj.drives[item].id, obj.drives[item].userPrincipal), node.nextSibling);
                            }
                        } else {
                            node.innerHTML = "<p>Derzeit sind keine Auftraege vorhanden.</p>";
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }

    function initializeDetails(startLat, startLng, endLat, endLng) {

        directionsDisplay = new google.maps.DirectionsRenderer();
        var endLoc = new google.maps.LatLng(endLat, endLng);

        var mapOptions = {
            zoom: 8,
            center: endLoc
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        directionsDisplay.setMap(map);

        calcRoute(new google.maps.LatLng(startLat, startLng), new google.maps.LatLng(endLat, endLng));
    }

    function onSuccessGeo(position) {
        lat = position.coords.latitude;
        lng = position.coords.longitude;

        fuelleAuftragAnzeigenUmkreis($scope.data.levelvalue, lat, lng);
        $scope.closeModal();               
    }

    function onErrorGeo(error) {
        var alertPopup = $ionicPopup.alert({
            title: 'Fehler',
            template: '' + error.message + '\n'
        });
    }
    function calcRoute(start, end) {
        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.BICYCLING,
            unitSystem: google.maps.UnitSystem.METRIC
        };

        directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(result);
                var distance = getDistanceFromRoute(result);
                var duration = getDurationFromRoute(result);
                console.log("Distance: " + distance + " Duration: " + duration);
            } else {
                console.log("error while calculating route");
            }
        });
    }
})





.controller('AppCtrl', function($scope, $ionicModal, $timeout, $state, $ionicPopup, $ionicHistory, $ionicTabsDelegate) {


    $scope.data = {
        auftragID: 0,
        mapInitialized: false
    };

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();


    /*_____   _____   _____   _____   _____   _____  
    /  ___/ /  ___| /  _  \ |  _  \ | ____| /  ___/ 
    | |___  | |     | | | | | |_| | | |__   | |___  
    \___  \ | |     | | | | |  ___/ |  __|  \___  \ 
     ___| | | |___  | |_| | | |     | |___   ___| | 
     /_____/ \_____| \_____/ |_|     |_____| /_____/  */





    $scope.bt_auftragAnnehmen = function() {

        driveAccept(fromLocalStorage("sessionUId"), $scope.data.auftragID, function(obj) {
            if (obj.errorcode == 0) {
                var alertPopup = $ionicPopup.alert({
                    title: 'Herzlichen Glückwunsch',
                    template: 'Sie haben den Auftrag angenommen!'
                });
                $state.go('app.meineAuftraege');
                fuelleMeineAuftraege();

                $ionicHistory.nextViewOptions({
                    disableAnimate: true,
                    disableBack: true
                });
            } else {
                var alertPopup = $ionicPopup.alert({
                    title: 'Fehler',
                    template: 'Der Auftrag konnte nicht angenommen werden.<br/>Systemnachricht: ' + obj.errormessage
                });
            }

        });
    };

    $scope.bt_logout = function() {
        var sessionID = fromLocalStorage("sessionID");
        var sessionUId = fromLocalStorage("sessionUId");
        var dUID = device.uuid;


        jQuery.ajax({
                type: "POST",
                url: "http://ba.tech-time.de/kurier/json.php",
                data: {
                    action: "logout",
                    sessionDeviceId: dUID,
                    sessionUId: sessionUId,
                    sessionId: sessionID
                },
                async: false
            })
            .done(function(data) {
                localStorage.clear();
                $state.go('login');
            });
    }

    $scope.bt_pwAendern = function() {
        var pw1 = document.getElementById("pwOne").value;
        var pw2 = document.getElementById("pwTwo").value;

        if (pw1 == "") {
            var alertPopup = $ionicPopup.alert({
                            title: 'Hinweis',
                            template: 'Bitte Passwort eingeben.'
                        });
        } else if (pw1 === pw2) {
            changePassword(pw1, function(obj) {
                if (obj) {
                    if (obj.errorcode == 0) {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Hinweis',
                            template: 'Ihr Passwort wurde geändert. Sie werden nun ausgeloggt.'
                        });
                        $state.go('login');
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Fehler beim Ändern des Passworts.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Fehler beim Ändern des Passworts.'
                    });
                }

            });

        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Passwörter stimmen nicht überein!'
            });
        }

    };


    $scope.goAuftragAnzeigen = function() {

        $state.go('app.auftraegeAnzeigen');
        $ionicHistory.nextViewOptions({
            disableAnimate: true,
            disableBack: true
        });

        if ($scope.data.mapInitialized == false) {
            $timeout(function() {
                $ionicTabsDelegate.select(1);

            }, 0);
            $timeout(function() {
                $ionicTabsDelegate.select(0);

                ;
            }, 0);
            $scope.data.mapInitialized = true;
        } else {
            $timeout(function() {
                $ionicTabsDelegate.select(0);

                ;
            }, 0);
        }
        fuelleAuftragAnzeigen();

    };

    $scope.goAuftragAufgeben = function() {
        $state.go('app.auftragAufgeben');
        $scope.gpsSearching = "Per GPS bestimmen";
        var date = new Date();
    };

    $scope.goMeineAuftraege = function() {
        $state.go('app.meineAuftraege');
        fuelleMeineAuftraege();
    };

    $scope.goProfilAendern = function() {
        $state.go('app.profilAendern');
        fuelleProfilAnzeigen();

    };

    /*
     _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
    |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
    | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
    |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
    | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
    |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */

    function auftragDetails(dID) {
        $state.go('app.auftragDetails');
        if (checkSession() == true) {

            showDrive(fromLocalStorage("sessionUId"), dID, function(obj) {
                if (obj) {
                    if (obj.errorcode == 0) {
                        initializeDetails(obj.drive.startLoc.gps_l, obj.drive.startLoc.gps_w, obj.drive.endLoc.gps_l, obj.drive.endLoc.gps_w);

                        document.getElementById("start").innerHTML = obj.drive.startLoc.street + " " + obj.drive.startLoc.number + "<br />" + obj.drive.startLoc.postal + " " + obj.drive.startLoc.city;
                        document.getElementById("ziel").innerHTML = obj.drive.endLoc.street + " " + obj.drive.endLoc.number + "<br />" + obj.drive.endLoc.postal + " " + obj.drive.endLoc.city;
                        document.getElementById("distanz").innerHTML = obj.drive.distance + "km";
                        document.getElementById("preis").innerHTML = obj.drive.price + "€";
                        document.getElementById("startzeit").innerHTML = fromUnixTimeToString(obj.drive.startTime);
                        document.getElementById("endzeit").innerHTML = fromUnixTimeToString(obj.drive.endTime);

                        $scope.data.auftragID = dID;
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Aktion gerade nicht möglich.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });
                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });
            $state.go('login');
        }
    }

   

    function createTable(entfernung, start, strecke, preis, endzeit, id, userPrincipal) {

        var div = document.createElement("div");
        div.className = "row";
        div.id = id;

        var div2 = document.createElement("div");
        div2.className = "col";
        if (entfernung == 0) {
            div2.innerHTML = "N/A";
        } else {
            div2.innerHTML = entfernung + " Km";
        }

        var div3 = document.createElement("div");
        div3.className = "col";
        div3.innerHTML = start;

        var div4 = document.createElement("div");
        div4.className = "col";
        div4.innerHTML = strecke + "km";

        var div5 = document.createElement("div");
        div5.className = "col";
        div5.innerHTML = preis + "€";

        var div6 = document.createElement("div");
        div6.className = "col";
        div6.innerHTML = fromUnixTimeToString(endzeit);


        div.appendChild(div2);
        div.appendChild(div3);
        div.appendChild(div4);
        div.appendChild(div5);
        div.appendChild(div6);

        $(div).bind('tap', function(event, ui) {

            auftragDetails(id);

        });

        if (userPrincipal == fromLocalStorage("sessionUId")) {
            div.className = "row stable-bg";
            console.log("eigener");
        }

        return div;
    }

    

    function driveChangeStatus(dID, status) {
        var dUID = device.uuid;
        var sessionID = fromLocalStorage("sessionID");
        var sessionUId = fromLocalStorage("sessionUId");
        $.post("http://ba.tech-time.de/kurier/json.php", {
                action: "driveChangeStatus",
                sessionDeviceId: dUID,
                sessionUId: sessionUId,
                sessionId: sessionID,
                driveId: dID,
                driveStatus: status
            },
            function(data) {
                var obj = jQuery.parseJSON(data);
                if (obj.errorcode == 0) {
                    $state.go('app.meineAuftraege');
                    fuelleMeineAuftraege();
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Auftrag konnte nicht aktualisiert werden.<br />Systemnachricht: ' + obj.errormessage
                    });
                }
            });
    }

    function fuelleProfilAnzeigen() {
        var dUID = device.uuid;
        var sessionId = fromLocalStorage("sessionID");
        var sessionUId = fromLocalStorage("sessionUId");
        if (checkSession() == true) {
            $.post("http://ba.tech-time.de/kurier/json.php", {
                    action: "userProfile",
                    sessionDeviceId: dUID,
                    sessionUId: sessionUId,
                    sessionId: sessionId
                },
                function(data) {
                    var obj = jQuery.parseJSON(data);
                    if (obj.errorcode == 0) {
                        document.getElementById('paeVorname').value = obj.userFirstname;
                        document.getElementById('paeNachname').value = obj.userLastname;
                        document.getElementById('paeEMail').value = obj.userEmail;
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Aktion leider nicht möglich.<br/>Systemnachricht: ' + obj.errormessage
                        });
                    }


                });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });
            $state.go('login');
        }
    }

    function fuelleMeineAuftraege() {
        if (checkSession() == true) {
            showAllUserDrives(fromLocalStorage("sessionUId"), function(obj) {
                if (obj) {
                    node = document.getElementById("rowsMeineAuftraege");
                    while (node.firstChild) {
                        node.removeChild(node.firstChild);
                    }
                    if (obj.errorcode == 0) {

                        if (obj.drives != "") {
                            for (var item in obj.drives) {
                                if (!isNumber(obj.drives)) {
                                    var typ = getAuftragsTyp(fromLocalStorage("sessionUId"), obj.drives[item].userAgent, obj.drives[item].userPrincipal);
                                    node.appendChild(createTableMeineAuftraege(typ, obj.drives[item].startLoc.city, obj.drives[item].endLoc.city, obj.drives[item].status, obj.drives[item].id), node.nextSibling);
                                }
                            }
                        } else {
                            node.innerHTML = "<p>Derzeit sind leider keine Auftraege vorhanden.</p>";
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }
                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });
                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }
    function createTableMeineAuftraege(typ, start, ziel, status, id) {

        var div = document.createElement("div");
        div.className = "row";
        div.id = id;

        var div2 = document.createElement("div");
        div2.className = "col col_narrow col_symbol";
        if (typ == "agent")
            div2.innerHTML = '<i class="icon ion-android-bicycle"></i>';
        else
            div2.innerHTML = '<i class="ion-ios-body"></i>';

        var div3 = document.createElement("div");
        div3.className = "col";
        div3.innerHTML = start;

        var div4 = document.createElement("div");
        div4.className = "col";
        div4.innerHTML = ziel;

        var div5 = document.createElement("div");
        div5.className = "col";
        div5.innerHTML = status;

        div.appendChild(div2);
        div.appendChild(div3);
        div.appendChild(div4);
        div.appendChild(div5);

        $(div).bind('tap', function(event, ui) {

            meineAuftraegeDetails(id);

        });

        return div;
    }

    function fuelleAuftragAnzeigen() {
        if (checkSession() == true) {
            showOpenDrives(fromLocalStorage("sessionUId"), 0, 0, 0, function(obj) {
                if (obj) {
                    node = document.getElementById("rows");
                    while (node.firstChild) {
                        node.removeChild(node.firstChild);
                    }
                    if (obj.errorcode == 0) {
                        if (obj.drives != "") {
                            for (var item in obj.drives) {
                                node.appendChild(createTable(0, obj.drives[item].endLoc.city, obj.drives[item].distance, obj.drives[item].price, obj.drives[item].endTime, obj.drives[item].id, obj.drives[item].userPrincipal), node.nextSibling);
                            }
                        } else {
                            node.innerHTML = "<p>Derzeit sind leider keine Auftraege vorhanden.</p>";
                        }
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }

                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }

    

    function meineAuftraegeDetails(dID) {
        $state.go('app.meineAuftraegeDetails');
        if (checkSession() == true) {

            showDrive(fromLocalStorage("sessionUId"), dID, function(obj) {
                if (obj) {
                    if (obj.errorcode == 0) {
                        initializeMeine(obj.drive.startLoc.gps_l, obj.drive.startLoc.gps_w, obj.drive.endLoc.gps_l, obj.drive.endLoc.gps_w);
                        var statusnr = obj.drive.statusnr;
                        var agent = obj.drive.userAgent;
                        var principal = obj.drive.userPrincipal;
                        var user = fromLocalStorage("sessionUId");

                        document.getElementById("start1").innerHTML = obj.drive.startLoc.street + " " + obj.drive.startLoc.number + "<br />" + obj.drive.startLoc.postal + " " + obj.drive.startLoc.city;
                        document.getElementById("ziel1").innerHTML = obj.drive.endLoc.street + " " + obj.drive.endLoc.number + "<br />" + obj.drive.endLoc.postal + " " + obj.drive.endLoc.city;
                        document.getElementById("distanz1").innerHTML = obj.drive.distance + "km";
                        document.getElementById("preis1").innerHTML = obj.drive.price + "€";
                        document.getElementById("startzeit1").innerHTML = fromUnixTimeToString(obj.drive.startTime);
                        document.getElementById("endzeit1").innerHTML = fromUnixTimeToString(obj.drive.endTime);
                        document.getElementById("status1").innerHTML = obj.drive.status;

                        var div = document.getElementById("meineAuftraegeDiv");
                        while (div.firstChild) {
                            div.removeChild(div.firstChild);
                        }

                        var btnone = document.createElement("button");
                        btnone.className = "button button-positive button-block";
                        btnone.id = "btnMeineAuftraege" + obj.drive.id;

                        if ((statusnr == 1 || statusnr == 2 || statusnr == 3) && user == principal) {
                            btnone.innerHTML = "Auftrag stornieren";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 6);
                            });
                            div.appendChild(btnone);
                        } else if ((statusnr == 3) && user == agent) {
                            btnone.innerHTML = "Auftrag starten";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 4);
                            });

                            div.appendChild(btnone);

                            var btntwo = document.createElement("button");
                            btntwo.className = "button button-positive button-block";
                            btntwo.id = "btnMeineAuftraegeTwo" + obj.drive.id;

                            btntwo.innerHTML = "Auftrag stornieren";
                            $(btntwo).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 2);
                            });

                            div.appendChild(btntwo);
                        } else if ((statusnr == 4) && user == agent) {
                            btnone.innerHTML = "Auftrag fertig";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 5);
                            });
                            div.appendChild(btnone);
                        } else if (statusnr == 5) {
                            btnone.innerHTML = "Auftrag bewerten";
                            $(btnone).bind('tap', function(event, ui) {
                                alert("TODO");
                            });
                            div.appendChild(btnone);
                        } else if (statusnr == 6 && user == principal) {
                            btnone.innerHTML = "Auftrag erneut einstellen";
                            $(btnone).bind('tap', function(event, ui) {
                                driveChangeStatus(obj.drive.id, 2);
                            });
                            div.appendChild(btnone);
                        }

                        $scope.data.auftragID = dID;
                    } else {
                        var alertPopup = $ionicPopup.alert({
                            title: 'Fehler',
                            template: 'Keine Daten vom Server.<br />Systemnachricht: ' + obj.errormessage
                        });
                    }




                } else {
                    var alertPopup = $ionicPopup.alert({
                        title: 'Fehler',
                        template: 'Keine Daten vom Server!'
                    });

                }
            });


        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Fehler',
                template: 'Session nicht vorhanden! Bitte neu Anmelden.'
            });

            $state.go('login');
        }
    }

function initializeDetails(startLat, startLng, endLat, endLng) {

        directionsDisplay = new google.maps.DirectionsRenderer();
        var endLoc = new google.maps.LatLng(endLat, endLng);

        var mapOptions = {
            zoom: 8,
            center: endLoc
        };
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
        directionsDisplay.setMap(map);

        calcRoute(new google.maps.LatLng(startLat, startLng), new google.maps.LatLng(endLat, endLng));
    }
function initializeMeine(startLat, startLng, endLat, endLng) {

        directionsDisplay = new google.maps.DirectionsRenderer();
        var endLoc = new google.maps.LatLng(endLat, endLng);

        var mapOptions = {
            zoom: 8,
            center: endLoc
        };
        var map = new google.maps.Map(document.getElementById('map-canvas3'), mapOptions);
        directionsDisplay.setMap(map);

        calcRoute(new google.maps.LatLng(startLat, startLng), new google.maps.LatLng(endLat, endLng));
    }
     function calcRoute(start, end) {


        var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.TravelMode.BICYCLING,
            unitSystem: google.maps.UnitSystem.METRIC
        };

        directionsService.route(request, function(result, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(result);
                var distance = getDistanceFromRoute(result);
                var duration = getDurationFromRoute(result);
                console.log("Distance: " + distance + " Duration: " + duration);
            } else {
                console.log("error while calculating route");
            }
        });
    }

});


/*
     _____   _   _   __   _   _____   _____   _   _____   __   _   _____  
    |  ___| | | | | |  \ | | /  ___| |_   _| | | /  _  \ |  \ | | /  ___/ 
    | |__   | | | | |   \| | | |       | |   | | | | | | |   \| | | |___  
    |  __|  | | | | | |\   | | |       | |   | | | | | | | |\   | \___  \ 
    | |     | |_| | | | \  | | |___    | |   | | | |_| | | | \  |  ___| | 
    |_|     \_____/ |_|  \_| \_____|   |_|   |_| \_____/ |_|  \_| /_____/  */




function addressToGps(address, callback) {
    var coordsString = false;
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        address: address

    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var coords = results[0].geometry.location;
            coordsString = coords.toString();
            var coordsLat = coords.lat();
            var coordsLng = coords.lng();
            // Die Callback function bekommt das LatLng-Objekt "coords" mitgegeben
            callback(coords);
        } else {
            callback(null);
            //alert(address + ' not found');
        }
    });
}

function changePassword(password, callback) {
    var dUID = device.uuid;
    var sessionId = fromLocalStorage("sessionID");
    var sessionUId = fromLocalStorage("sessionUId");

    $.post("http://ba.tech-time.de/kurier/json.php", {
            action: "changePassword",
            userPassword: password,
            sessionDeviceId: dUID,
            sessionUId: sessionUId,
            sessionId: sessionId
        },
        function(data) {
            var obj = jQuery.parseJSON(data);
            callback(obj);
        });
}

function checkSession() {
    var dUID = device.uuid;
    var sessionId = fromLocalStorage("sessionID");
    var sessionUId = fromLocalStorage("sessionUId");
    var ret = false;
    jQuery.ajax({
            type: "POST",
            url: "http://ba.tech-time.de/kurier/json.php",
            data: {
                action: "checkSession",
                sessionDeviceId: dUID,
                sessionUId: sessionUId,
                sessionId: sessionId
            },
            async: false
        })
        .done(function(data) {
            var obj = jQuery.parseJSON(data);
            if (obj.errorcode == "0") {
                ret = true;
            }
        });

    return ret;
}

function driveAccept(UID, dID, callback) {
    var dUID = device.uuid;
    var sessionID = fromLocalStorage("sessionID");

    $.post("http://ba.tech-time.de/kurier/json.php", {
            action: "driveAccept",
            sessionDeviceId: dUID,
            sessionUId: UID,
            sessionId: sessionID,
            driveId: dID
        },
        function(data) {
            var obj = jQuery.parseJSON(data);
            callback(obj);
        });
}

function driveAdd(UID, distance, endLocation, endTime, price, startLocation, startTime, status, callback) {
    var dUID = device.uuid;
    var sessionID = fromLocalStorage("sessionID");

    //alert(UID + " " + distance + " " + endLocation + " " + endTime + " " + price + " " + startLocation + " " + startTime + " " + status);
    jQuery.ajax({
            type: "POST",
            url: "http://ba.tech-time.de/kurier/json.php",
            data: {
                action: "driveAdd",
                sessionDeviceId: dUID,
                sessionUId: UID,
                sessionId: sessionID,
                driveDistance: distance,
                driveEndLocation: endLocation,
                driveEndTime: endTime,
                drivePrice: price,
                driveStartLocation: startLocation,
                driveStartTime: startTime,
                driveStatus: status
            },
            async: false
        })
        .done(function(data) {
            var obj = jQuery.parseJSON(data);


            console.log(obj);
            callback(obj);

        });
}

function fromLocalStorage(key) {
    return window.localStorage.getItem(key);
}

function fromUnixTimeToString(unixTime) {
    var date = new Date(unixTime * 1000);

    // year part from the timestamp
    var year = date.getFullYear();

    // month part from the timestamp
    var month = "0" + date.getMonth();

    // day part from the timestamp
    var day = "0" + date.getDate();

    // hours part from the timestamp
    var hours = "0" + date.getHours();
    // minutes part from the timestamp
    var minutes = "0" + date.getMinutes();


    // Zeigt Zeit in diesem Format an: YYYY-MM-DD HH:MM:SS
    var formattedTime =
        day.substr(day.length - 2) + "." + month.substr(month.length - 2) + "." + year.toString().substr(2) + " " +
        +hours.substr(hours.length - 2) + ":" + minutes.substr(minutes.length - 2);

    return formattedTime;
}

function fuelleOrtFelder(obj) {
    if (fromLocalStorage("fromOrTo") == "from") {

        if (obj.straße != "")
            document.getElementById('auftrag.from.strasse').value = obj.straße;
        if (obj.hausnummer != "")
            document.getElementById('auftrag.from.hausn').value = obj.hausnummer;
        if (obj.plz != "")
            document.getElementById('auftrag.from.plz').value = obj.plz;
        if (obj.stadt != "")
            document.getElementById('auftrag.from.ort').value = obj.stadt;
    } else if (fromLocalStorage("fromOrTo") == "to") {
        if (obj.straße != "")
            document.getElementById('auftrag.to.strasse').value = obj.straße;
        if (obj.hausnummer != "")
            document.getElementById('auftrag.to.hausn').value = obj.hausnummer;
        if (obj.plz != "")
            document.getElementById('auftrag.to.plz').value = obj.plz;
        if (obj.stadt != "")
            document.getElementById('auftrag.to.ort').value = obj.stadt;
    }
}

function getAuftragsTyp(uid, agent, principal) {
    if (uid == agent)
        return "agent";
    else
        return "principal";
}

function getDistanceFromRoute(start, end, callback) {

    var directionsDisplay;
    var directionsService = new google.maps.DirectionsService();

    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.TravelMode.BICYCLING,
        unitSystem: google.maps.UnitSystem.METRIC
    };

    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            var distance = getDistanceFRoute(result);
            var duration = getDurationFRoute(result);
            console.log("Distance: " + distance + " Duration: " + duration);

            callback(distance);
        } else {
            console.log("Error while calculating route");
        }
    });
}

function getDistanceFRoute(result) {
    return result.routes[0].legs[0].distance.text;
}

function getDurationFRoute(result) {
    return result.routes[0].legs[0].duration.text;
}

function getObjectFromAddress(result) {
    fields = 'name,city,state,country,address,street,route,zip,countie'.split(',');
    for (var x in fields)
        eval('var ' + fields[x] + ' = \'\';');

    place = result;
    name = place.name
    var address = new Object;
    for (x = 0; x < place.address_components.length; x++) {
        types = place.address_components[x].types;
        sn = place.address_components[x].short_name;
        for (y = 0; y < types.length; y++) {
            currentType = types[y];
            if (currentType == 'country') {
                country = sn;

                address.land = country;
            } else if (currentType == 'administrative_area_level_1') {
                state = sn;

                address.bundesland = state;
            } else if (currentType == 'administrative_area_level_2') {
                countie = sn;

                address.bezirk = countie;
            } else if (currentType == 'locality') {
                city = sn;

                address.stadt = city;
            } else if (currentType == 'postal_code') {
                zip = sn;

                address.plz = zip;
            } else if (currentType == 'street_number') {
                streetnumber = sn;

                address.hausnummer = streetnumber;
            } else if (currentType == 'route') {
                route = sn;
                //Nils: TODO: Das finde ich so relativ gefährlich. Lieber ss nehmen.
                address.straße = route;
            }
        }
    }

    console.log("Land:" + address.land + "     Bezirk:" + address.bezirk + "     Stadt:" + address.stadt + "     Bundesland:" + address.bundesland + "     Postleitzahl:" + address.plz + "     Hausnummer:" + address.hausnummer + "    Straße:" + address.straße);
    return address;
}

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function locationAdd(UID, city, description, lng, lat, number, postal, street) {
    var dUID = device.uuid;
    var sessionID = fromLocalStorage("sessionID");

    var locID = 0;
    jQuery.ajax({
        type: "POST",
        url: "http://ba.tech-time.de/kurier/json.php",
        data: {
            action: "locationAdd",
            sessionDeviceId: dUID,
            sessionUId: UID,
            sessionId: sessionID,
            locationGpsL: lat,
            locationGpsW: lng,
            locationDescription: description,
            locationCity: city,
            locationNumber: number,
            locationPostal: postal,
            locationStreet: street
        },
        async: false
    }).done(function(data) {

        console.log(data);

        var obj = jQuery.parseJSON(data);
        if (obj.errorcode == 0) {
            locID = obj.locationId;
        } else {
            locID = 0;
        }

        console.log(obj.locationId);
    });

    return locID;
}

function showAllUserDrives(UID, callback) {
    var dUID = device.uuid;
    var sessionID = fromLocalStorage("sessionID");

    $.post("http://ba.tech-time.de/kurier/json.php", {
            action: "showAllUserDrives",
            sessionDeviceId: dUID,
            sessionUId: UID,
            sessionId: sessionID,
            driveStatus: "",
            driveUserType: ""
        },
        function(data) {
            var obj = jQuery.parseJSON(data);
            callback(obj);

        });
}

function showDrive(UID, dID, callback) {
    var dUID = device.uuid;
    var sessionID = fromLocalStorage("sessionID");
    $.post("http://ba.tech-time.de/kurier/json.php", {
            action: "showDrive",
            sessionDeviceId: dUID,
            sessionUId: UID,
            sessionId: sessionID,
            driveId: dID
        },
        function(data) {
            var obj = jQuery.parseJSON(data);
            callback(obj);
        });
}

function showOpenDrives(UID, driveRange, driveLat, driveLng, callback) {
    var dUID = device.uuid;

    var sessionID = fromLocalStorage("sessionID");
    $.post("http://ba.tech-time.de/kurier/json.php", {
            action: "showOpenDrives",
            sessionDeviceId: dUID,
            sessionUId: UID,
            sessionId: sessionID,
            driveRange: driveRange,
            driveLat: driveLat,
            driveLong: driveLng
        },
        function(data) {

            var obj = jQuery.parseJSON(data);
            console.log(data);
            callback(obj);

        });
}

function toLocalStorage(key, value) {
    window.localStorage.setItem(key, value);
}

function toUnixTime(strDate, strTime) {

    datum = strDate.replace(".", "-");

    var date = strDate.split("-");
    var yyyy = date[0];
    var mm = date[1];
    var dd = date[2];

    time = strTime.replace(".", "-");
    datum = dd + "-" + mm + "-" + yyyy + " " + time;


    date1 = datum.replace(/(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3");

    var unixtime = Date.parse(date1) / 1000;
    console.log(unixtime);
    return unixtime;
}
